package com.android.ailaoshan.sound;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.ailaoshan.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class PlayActivity extends AppCompatActivity {

    private Context mContext;

    private MediaPlayer mediaPlayer;
    private Timer timer;
    private MyHandler myHandler;
    private SimpleDateFormat formatter = new SimpleDateFormat("mm:ss", Locale.getDefault());

    private SeekBar seekBar;
    private TextView currentTime;
    private TextView allTime;
    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sound_play_activity);

        mContext = PlayActivity.this;
    }


    @Override
    protected void onResume(){
        super.onResume();

        String filePath = getIntent().getStringExtra("filePath");
        int saveType = getIntent().getIntExtra("saveType", 3);
        File file = new File(filePath);
        if( file.exists() ){
            mediaPlayer = new MediaPlayer();
            myHandler = new MyHandler();

            seekBar = findViewById(R.id.sound_play_seekBar);
            currentTime = findViewById(R.id.sound_play_currentTime);
            allTime = findViewById(R.id.sound_play_allTime);
            FloatingActionButton playControl = findViewById(R.id.sound_play_control);
            toolbar = findViewById(R.id.sound_play_toolbar);
            TextView deletePicture = findViewById(R.id.picture_play_delete);

            if(saveType == 3){
                deletePicture.setVisibility(View.INVISIBLE);
            }

            // 准备播放，出现异常则退出
            mediaPlayer.reset();
            try {
                mediaPlayer.setDataSource(filePath);
                mediaPlayer.prepare();
            } catch (IOException e) {
                e.printStackTrace();
                setResult(601);
                finish();
            }

            // 播放按钮点击监听
            playControl.setOnClickListener(
               (v) -> {
                    if(mediaPlayer != null){
                        // 正在播放，暂停
                        if(mediaPlayer.isPlaying()){
                            mediaPlayer.pause();
                            playControl.setImageResource(R.drawable.sound_control_play);
                        }
                        // 开始播放
                        else{
                            mediaPlayer.start();
                            playControl.setImageResource(R.drawable.sound_control_pause);
                        }
                    }
                }
            );

            // 播放失败监听，播放失败退出
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    Toast.makeText(mContext,"尝试播放失败",Toast.LENGTH_SHORT).show();
                    setResult(601);
                    finish();
                    return false;
                }
            });

            // 滑动条监听
            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {}

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {}

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    int progress = seekBar.getProgress();
                    mediaPlayer.seekTo(progress);
                }
            });

            // 播放结束监听
            mediaPlayer.setOnCompletionListener(
               (mp) -> playControl.setImageResource(R.drawable.sound_control_play)
            );


            // 删除图片监听
            deletePicture.setOnClickListener(
               (v) -> {
                   if(mediaPlayer != null){
                       mediaPlayer.stop();
                   }
                   // 获取文件名
                   String deleteName = file.getName();



                   // 设置返回数据
                   Intent intent = new Intent();
                   intent.putExtra("deleteName",deleteName);
                   setResult(602,intent);

                   finish();
               }
            );

            // 添加定时任务
            addTimer();

        }else{
            Toast.makeText(mContext,"文件不存在",Toast.LENGTH_SHORT).show();
            setResult(601);
            finish();
        }

        // 返回监听
        toolbar.setNavigationOnClickListener(
           (v) -> {
               setResult(601);
               finish();
           }
        );
    }

    /**
     * 添加计时器
     */
    private void addTimer(){
        if(timer == null){
            timer = new Timer();
        }
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if(mediaPlayer != null){
                    // 音频总时长
                    int all = mediaPlayer.getDuration();
                    int current = mediaPlayer.getCurrentPosition();
                    Message msg = myHandler.obtainMessage();

                    Bundle bundle = new Bundle();
                    bundle.putInt("all",all);
                    bundle.putInt("current",current);
                    msg.setData(bundle);

                    if(myHandler != null){
                        myHandler.sendMessage(msg);
                    }
                }
            }
        },5,500);// 延时5秒执行，以后每500ms执行一次
    }

    /**
     * 设置处理器
     */
    private class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg){
            Bundle bundle = msg.getData();
            int all = bundle.getInt("all");
            int current = bundle.getInt("current");

            if(seekBar != null){
                // 刷新滑块进度
                seekBar.setMax(all);
                seekBar.setProgress(current);
            }
            // 当前时间
            if( (currentTime != null) && (formatter != null) ){
                currentTime.setText(formatter.format(current));
            }
            // 总时间
            if( (allTime != null) && (formatter != null) ){
                allTime.setText(formatter.format(all));
            }
        }
    }


    @Override
    protected void onDestroy(){
        super.onDestroy();

        mediaPlayer.stop();
        mediaPlayer.release();

        mContext = null;
        myHandler = null;
        formatter = null;
        mediaPlayer = null;
        timer = null;
        seekBar = null;
    }
}
